<?php

namespace app\unify\middleware;

use app\unify\model\Api;
use app\unify\model\User;
use app\unify\traits\Result;
use think\Request;
use think\Response;

class UserLog
{
    use Result;

    public function handle(Request $r, \Closure $next)
    {
        /**
         * @var $response Response|string
         */
        $response = $next($r);

        if ($r->isAjax()) {
            return $response;
        }

        $resData = $response->getData();

        if(is_string($resData)){
            preg_match("/<[^<]+>/", $resData, $matches);
            if (count($matches) !== 0) {
                return $response;
            }
        }


        if (!is_string($resData)) {
            $resData = json_encode($response->getData(), JSON_UNESCAPED_UNICODE);
        }

        $params = [
            'header' => $r->header(),
            'cookie' => $r->cookie(),
            'query' => $r->query(),
            'get' => $r->get(),
            'post' => $r->post(),
        ];


        \app\unify\model\UserLog::create([
            'user_id' => User::id(),
            'url' => $r->url(),
            'description' => Api::where('path', '=', $r->baseUrl())->value("description") ?: "",
            'request' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'response' => $resData,
            'user_agent' => $r->header('user-agent'),
            'ip' => $r->ip(),
        ]);

        return $response;

    }
}